﻿using System;
using VideoServices.Business.Facade;
using VideoServices.Domain.Entities;
using VideoServices.Services.Dto;
using VideoServices.Services.Interface;
using VideoServices.Services.Response;
using VideoServices.Services.Response.Extension;
using VideoServices.Services.Translation;
using VideoServices.Services.Translation.Base;
using VideoServices.Services.Translation.Factory;

namespace VideoServices.Services
{
    public class OrderService : IOrderService
    {
        #region Implementation of IOrderService

        /// <summary>
        /// Gets the order by id.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns></returns>
        public Response<OrderDto> GetOrderById(Guid id)
        {
            var response = new Response<OrderDto>();
            response.IsSuccessful = true;
            try
            {
                var facade = VideoServicesFacade.Instance;
                Order order = facade.GetOrderById(id);
                ITranslator translator = TranslatorFactory.GetTranslatorByType(typeof(OrderTranslator));
                response.ResponseObject = translator.TranslateToDto<Order, OrderDto>(order);
            }
            catch (Exception ex)
            {
                response.IsSuccessful = false;
                response.Errors.Add(new Error("Fatal error occured.", ex.Message));
            }
            return response;
        }

        /// <summary>
        /// Creates the order.
        /// </summary>
        /// <param name="newOrder">The new order.</param>
        /// <returns></returns>
        public Response<OrderDto> CreateOrder(OrderDto newOrder)
        {
            var response = new Response<OrderDto>();
            response.IsSuccessful = true;
            try
            {
                var facade = VideoServicesFacade.Instance;
                ITranslator translator = TranslatorFactory.GetTranslatorByType(typeof(OrderTranslator));
                Order orderEntity = translator.TranslateToEntity<OrderDto, Order>(newOrder);
                Order savedOrder = facade.CreateOrder(orderEntity);
                response.ResponseObject = translator.TranslateToDto<Order, OrderDto>(savedOrder);
                response.Messages.AddSuccessfulSaveMessage("Order");
            }
            catch (Exception ex)
            {
                response.IsSuccessful = false;
                response.Errors.Add(new Error("Fatal error occured.", ex.Message));
            }
            return response;
        }

        #endregion
    }
}
